<template>
  <a-layout>
    <a-layout-sider
      :style="{
        background: '#fff',
        width: '250px',
        height: tableHeight + 'px',
        overflow: 'auto',
        'overflow-x': 'auto'
      }"
      width="250"
    >
      <div style="min-width: max-content">
        <a-menu
          mode="inline"
          :selectedKeys="selectedKeys"
          :openKeys="openKeys"
          @select="handleMenuSelect"
          @openChange="handleOpenChange"
        >
          <a-sub-menu
            key="summary"
            :title="`年度维保任务`"
          >
            <a-menu-item key="all-data-summary">
              年度维保数据汇总
              <span style="color: green; margin-left: 10px">{{ totalDetectedCount }}</span>
              /
              <span style="color: red">{{ totalNotDetectedCount }}</span>
              /
              <span style="color: black">{{ totalTotalCount }}</span>
            </a-menu-item>
            <a-menu-item
              v-for="(item, index) in menuItems"
              :key="item.equipment_type"
            >
              {{ item.equipment_type }}
              <span style="color: green">{{ item.detected_count }}</span>
              /
              <span style="color: red">{{ item.not_detected_count }}</span>
              /
              <span style="color: black">{{ item.total_count }}</span>
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </div>
      <div style="min-width: max-content">
        <a-menu
          mode="inline"
          :selectedKeys="selectedKeys"
          :openKeys="openKeys"
          @openChange="handleOpenChange"
          @select="handleMonthSelect"
        >
          <a-sub-menu
            key="monthly-summary"
            :title="`月度维保任务`"
          >
            <a-sub-menu
              v-for="(monthData, month) in monthMenuData"
              :key="month"
              :title="month"
            >
              <a-menu-item
                v-for="(item, index) in monthData"
                :key="month + '-' + item.equipment_type"
              >
                {{ item.equipment_type }}
                <span style="color: green;margin-left: 5px">{{ item.detected_count }}</span>
                /
                <span style="color: red">{{ item.not_detected }}</span>
                /
                <span style="color: black">{{ item.avg_per_month }}</span>
              </a-menu-item>
            </a-sub-menu>
          </a-sub-menu>
        </a-menu>
      </div>
      
    </a-layout-sider>
    <a-layout-content>
      <div>
        <BasicTable v-if="showBasicTable" ref="tableRef" @register="registerTable">
          <template #tableTitle>
            <Icon :icon="getTitle.icon" class="m-1 pr-1" />
            <span> 年度维保任务 </span>
          </template>
          <template #firstColumn="{ record }">
            <a @click="handleForm({ tid: record.tid })">
              {{ record.maintenanceId }}
            </a>
          </template>
        </BasicTable>
        <MonthList v-if="showMonthList" 
        :selectedMonth="selectedMonth"  
        :maintenanceId="props.tid"
        :EquipmentTypeRef="EquipmentTypeRef"
        :EquipmentTypeCode="EquipmentTypeCode"
        />
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts" setup name="ViewsMaintenanceManagementInMaintenanceInfoDataList">
import {
  unref,
  defineProps,
  onMounted,
  ref,
  computed,
  watch,
  Recordable,
  nextTick
} from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import {
  inMaintenanceInfoDataDelete,
  inMaintenanceInfoDataListData,
  getEquipmentTotalByType,
  getEquipmentTotalByMonth
} from '/@/api/maintenance.management/inMaintenanceInfoData';
import { useDrawer } from '/@/components/Drawer';
import { FormProps } from '/@/components/Form';
import MonthList from '/@/views/maintenance/management/inMaintenanceInfoData/component/monthList.vue';
import {
  Layout,
  LayoutContent,
  LayoutHeader,
  LayoutFooter,
  LayoutSider,
  Menu,
  MenuItem,
  MenuProps,
  ItemType,
  Dropdown,
  DropdownButton,
  Tree
} from 'ant-design-vue';
import InputForm from './form.vue';

const { t } = useI18n('maintenance.management.inMaintenanceInfoData');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);
const selectedMonth = ref('');
const EquipmentTypeCode = ref('');
const EquipmentTypeRef = ref('');
// const DetectedStatus= ref('');

const getTitle = {
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: meta.title || t('年度维保设备信息记录'),
};

const props = defineProps({
  tid: Number,
});

const TaskData = ref('');
const TaskParams = computed(() => {
  return {
    equipmentName: TaskData.value,
  };
});

const EquipmentType = ref('');

const searchForm: FormProps = {
  baseColProps: { md: 8, lg: 6 },
  labelWidth: 90,
  schemas: [
    {
      label: t(''),
      field: 'state',
      component: 'Select',
      componentProps: {
        placeholder: t('请输入检测状态'),
        options: [
          { label: '已检测', value: '已检测' },
          { label: '未检测', value: '未检测' },
          // { label: '已接受信号', value: '已接受信号' },
        ],
        onSelect:(item)=>{
           console.log(item)
          // DetectedStatus.value = item
        }
      },
    },
    {
      label: t(''),
      field: 'equipmentName',
      component: 'Input',
      componentProps: {
        placeholder: t('请输入设备名称'),
      },
    },
  ],
};

const tableColumns: BasicColumn[] = [
  {
    title: t('设备名称'),
    dataIndex: 'equipmentName',
    key: 'a.equipment_name',
    sorter: true,
    width: 120,
    align: 'left',
  },
  {
    title: t('设备类型名称'),
    dataIndex: 'equipmentType',
    key: 'a.equipment_type',
    sorter: true,
    width: 120,
    align: 'left',
  },
  // {
  //   title: t('设备类型编码'),
  //   dataIndex: 'equipmentTypeCode',
  //   key: 'a.equipment_type_code',
  //   sorter: true,
  //   width: 120,
  //   align: 'left',
  // },
  {
    title: t('检测状态'),
    dataIndex: 'state',
    key: 'a.state',
    sorter: true,
    width: 120,
    align: 'left',
  },
  {
    title: t('设备地址'),
    dataIndex: 'equipmentAddress',
    key: 'a.equipment_address',
    sorter: true,
    width: 120,
    align: 'left',
  },
  {
    title: t('检测时间'),
    dataIndex: 'firstDetectionTime',
    key: 'a.first_detection_time',
    sorter: true,
    width: 160,
    align: 'left',
  },
];

const tableRef = ref(null);
const tableHeight = ref(0);

const [registerTable, { reload }] = useTable({
  api: inMaintenanceInfoDataListData,
  beforeFetch: (params) => {
    // 合并参数
    params = {
      ...params,
      maintenanceId: props.tid,
      equipmentType: EquipmentType.value,
    };
    return params;
  },
  columns: tableColumns,
  formConfig: searchForm,
  showTableSetting: true,
  useSearchForm: true,
  canResize: true,
});

const [registerDrawer, { openDrawer }] = useDrawer();

function handleForm(record: Recordable) {
  openDrawer(true, record);
}

async function handleDelete(record: Recordable) {
  const params = { tid: record.tid };
  const res = await inMaintenanceInfoDataDelete(params);
  showMessage(res.message);
  handleSuccess(record);
}

function handleSuccess(record: Recordable) {
  reload({ record });
  // 重新计算表格高度
  nextTick(() => {
    if (tableRef.value) {
      tableHeight.value = tableRef.value.$el.offsetHeight;
    }
  });
}

const tidValue = ref(props.tid);
watch(() => props.tid, (newValue) => {
  tidValue.value = newValue;
  console.log('tid变化了，新值为:', newValue);
  if (newValue!== null) {
    reload();
    fetchMenuData();
    fetchMonthMenuData(); 
    // 重新计算表格高度
    nextTick(() => {
      if (tableRef.value) {
        tableHeight.value = tableRef.value.$el.offsetHeight;
      }
    });
  }
});

const menuItems = ref<any[]>([]);
const selectedKeys = ref<string[]>([]);
const openKeys = ref<string[]>([]);

const showBasicTable = ref(true);
const showMonthList = ref(false);

const handleMenuSelect = (e) => {
  if (e.key === 'all-data-summary') {
    console.log('点击了数据汇总');
    // 点击数据汇总时，清空设备类型筛选条件
    EquipmentType.value = '';
    // 可以根据需要添加其他清空筛选条件的逻辑
  } else if (e.key ==='summary') {
    console.log('点击了年度维保任务汇总');
    EquipmentType.value = '';
  } else if (e.key ==='monthly-all-data-summary') {
    console.log('点击了月度维保任务汇总');
    EquipmentType.value = '';
  } else {
    console.log('点击了菜单项:', e.key);
    EquipmentType.value = e.key;
  }
  showBasicTable.value = true;
  showMonthList.value = false;
  reload();
  selectedKeys.value = [e.key];
  // 重新计算表格高度
  nextTick(() => {
    if (tableRef.value) {
      tableHeight.value = tableRef.value.$el.offsetHeight;
    }
  });
};
const handleOpenChange = (keys: string[]) => {
  openKeys.value = keys;
};

const totalDetectedCount = ref(0);
const totalNotDetectedCount = ref(0);
const totalTotalCount = ref(0);

const fetchMenuData = async () => {
  try {
    if (tidValue.value!== null) {
      const response = await getEquipmentTotalByType({ maintenanceId: tidValue.value });
      const uniqueTypes: Record<string, { 
        equipment_type: string; 
        total_count: number; 
        detected_count: number; 
        not_detected_count: number 
      }> = {};
      let totalDetected = 0;
      let totalNotDetected = 0;
      let totalTotal = 0;

      response.forEach((item) => {
        if (item.equipment_type) {
          if (!uniqueTypes[item.equipment_type]) {
            uniqueTypes[item.equipment_type] = {
              equipment_type: item.equipment_type,
              total_count: item.total_count || 0,
              detected_count: item.detected_count || 0,
              not_detected_count: item.not_detected_count || 0,
            };
          } else {
            uniqueTypes[item.equipment_type].total_count += item.total_count || 0;
            uniqueTypes[item.equipment_type].detected_count += item.detected_count || 0;
            uniqueTypes[item.equipment_type].not_detected_count += item.not_detected_count || 0;
          }
        }
        totalDetected += item.detected_count || 0;
        totalNotDetected += item.not_detected_count || 0;
        totalTotal += item.total_count || 0;
      });

      menuItems.value = Object.values(uniqueTypes);
      totalDetectedCount.value = totalDetected;
      totalNotDetectedCount.value = totalNotDetected;
      totalTotalCount.value = totalTotal;
    }
  } catch (error) {
    console.error('获取菜单数据失败:', error);
  }
};

const monthMenuData = ref<Record<string, any[]>>({});

const fetchMonthMenuData = async () => {
  try {
    if (tidValue.value!== null) {
      const response = await getEquipmentTotalByMonth({ id: tidValue.value });
      monthMenuData.value = response;
    }
  } catch (error) {
    console.error('获取菜单数据失败:', error);
  }
};

const handleMonthSelect = (e) => {
  const lastIndex = e.key.lastIndexOf('-');
  const month_start = e.key.slice(0, lastIndex);
  const equipment_type = e.key.slice(lastIndex + 1);

  selectedMonth.value = month_start;
  EquipmentTypeRef.value = equipment_type;

  // 根据 month_start 和 equipment_type 从 monthMenuData 中获取 equipment_type_code
  const monthData = monthMenuData.value[month_start];
  const item = monthData.find(i => i.equipment_type === equipment_type);
  const equipment_type_code = item? item.equipment_type_code : '';
  EquipmentTypeCode.value = equipment_type_code;

  showBasicTable.value = false;
  showMonthList.value = true;
  console.log('点击了月度菜单项:', selectedMonth.value, equipment_type, equipment_type_code);

  // 重新计算表格高度
  nextTick(() => {
    if (tableRef.value) {
      tableHeight.value = tableRef.value.$el.offsetHeight;
    }
  });
};


onMounted(async () => {
  console.log('组件挂载时tid的值为:', tidValue.value);
  if (tidValue.value!== null) {
    reload();
    await fetchMenuData();
    await fetchMonthMenuData(); 
    // 等待表格渲染完成后获取高度
    nextTick(() => {
      if (tableRef.value) {
        tableHeight.value = tableRef.value.$el.offsetHeight;
      }
    });
  }
});
</script>

<style scoped lang="less">
.a-layout {
  display: flex;
}

.a-layout-sider {
  overflow: auto;
}

.a-layout-content {
  flex: 1;
  overflow: auto;
}
</style>    